<?php

class PostController extends Controller
{
	public function actionIndex()
	{
	   $model = new Post();
      $page = isset($_GET['page']) ? ((int) $_GET['page']) : 1;
      $limit = 10;
      $offset = $page*$limit - $limit;
      $criteria = new CDbCriteria();
      if(isset($_GET['Post'])){
         $model->attributes = $_GET['Post'];
         if($model->post_cat_id > 0){
            $criteria->addCondition('post_cat_id =' . $model->post_cat_id);
         }
         if($model->post_prv_id > 0){
            $criteria->addCondition('post_prv_id =' . $model->post_prv_id);
         }
         if($model->post_dis_id > 0){
            $criteria->addCondition('post_dis_id =' . $model->post_dis_id);
         }
         if($model->post_prj_id > 0){
            $criteria->addCondition('post_prj_id =' . $model->post_prj_id);
         }
         if($model->post_area != 0){
            $area = explode(',',$model->post_area);
            if($area[0] > 0){
               $criteria->addCondition('post_area >=' . $area[0]);
            }
            if($area[1] > 0){
               $criteria->addCondition('post_area <=' . $area[1]);
            }
         }
         
	   }
      $count = $model->count($criteria);  
      $criteria->offset = $offset;
      $criteria->limit = $limit;
      $models = $model->findAll($criteria);
      //CVarDumper::dump($model,10,true);die();
      
      $url_current = $_SERVER['REQUEST_URI'];
      
      $end_of_url = strpos($url_current,'&yt0');
      if($end_of_url){
         $url_current = substr($url_current,0,$end_of_url);
      }
      $pagination = new Zebra_Pagination();
      $pagination->records($count);
      $pagination->records_per_page($limit);
		$this->render('index',array(
         'model' => $model,
         'models' => $models,
         'pagination' => $pagination,
      ));
	}
   
   /**
    * Display page detail
   */
   public function actionDetail(){
      $id = Yii::app()->request->getParam('id',0);      
      $model = Post::model()->with('province','district','project','post_image')->findByPk($id);
      //CVarDumper::dump($model,10,true);die();
      $models = array(); //Danh sach nhung tin lien quan
      if($model != null){
         $this->pageTitle = $model->post_title;
         
         //Lay ra danh sach nhung tin lien quan
         $criteria = new CDbCriteria();
         $criteria->addCondition('post_cat_id = ' . $model->post_cat_id);
         $criteria->addCondition('post_id <>' . $model->post_id);
         $criteria->offset = 0;
         $criteria->limit = 5;         
         $models = $model->findAll($criteria);
      }
         
      $this->render('detail',array(
         'model' => $model,
         'models' => $models,
      ));
   }
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      $model = new Post();
      $PostImage = new PostImage();
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Post'])){
         $model->attributes = $_POST['Post'];
         $model->post_date_create = time();
         $model->post_date_update = $model->post_date_create;
         $model->post_use_id = Yii::app()->user->id;
         if($model->validate()){
            if($model->save()){
               Yii::app()->user->setFlash('success','Đăng tin thành công');
               //Upload image
               $images = CUploadedFile::getInstancesByName('PostImage');
               if(isset($images) && count($images)> 0)
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/post/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $post = Post::Model()->findByPk($model->post_id);
                           $post->post_avatar = $fileName;
                           $post->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(100);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);
                        $PostImage->setIsNewRecord(true);
                        $PostImage->post_img = $fileName;
                                                
                        $PostImage->post_id = $model->post_id;
                        if($PostImage->validate())
                           $PostImage->save();
                        else
                        {
                           CVarDumper::dump($PostImage->errors,10,true);
                        }                  
                     }                
                  }
                  $model->unsetAttributes();
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      unset($tree_cate[0]);
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $this->pageTitle = 'Đăng bài';
      //$this->layout = '//layouts/cms/create';
      $this->render('create',array('model'=>$model,
                                    'PostImage' => $PostImage,
                                    'list_province' => $list_province,
                                    'tree_cate' => $tree_cate,
                                    'message' => $message));
   }
   
   /**
    * 
    * Display page create
   */
   public function actionEdit($id){
      $model = Post::model()->findByPk($id);
      if($model->post_use_id != Yii::app()->user->id){
         $this->redirect(Yii::app()->request->hostInfo);
      }
      $PostImage = new PostImage();
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Post'])){
         $old_avatar = $model->post_avatar;
         $model->attributes = $_POST['Post'];
         $images = CUploadedFile::getInstancesByName('PostImage');
         if(count($images) == 0){
            $model->post_avatar = $old_avatar;
         }
         $model->post_date_update = time();
         if($model->validate()){
            if($model->save()){
               Yii::app()->user->setFlash('success','Cập nhật thành công');
               
               //Upload image
               if(isset($images) && count($images)> 0){
                  //Xoa nhung anh cu
                  $PostImage->deleteAllByAttributes(array(
                     'post_id' => $id,
                  ));
                  
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/post/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $post = Post::Model()->findByPk($model->post_id);
                           $post->post_avatar = $fileName;
                           $post->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(100);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);
                        $PostImage->setIsNewRecord(true);
                        $PostImage->post_img = $fileName;
                                                
                        $PostImage->post_id = $model->post_id;
                        if($PostImage->validate())
                           $PostImage->save();
                        else
                        {
                           CVarDumper::dump($PostImage->errors,10,true);
                        }                  
                     }                
                  }
               }
                  $model->unsetAttributes();
            }
         }
            
         if($action_user == 'save'){
            $this->redirect('/index.php/admin/'.$this->id);
         }
         }
      
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      unset($tree_cate[0]);
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $this->pageTitle = 'Chỉnh sửa bài đăng';
      //$this->layout = '//layouts/cms/create';
      $this->render('create',array('model'=>$model,
                                    'PostImage' => $PostImage,
                                    'list_province' => $list_province,
                                    'tree_cate' => $tree_cate,
                                    'message' => $message));
   }
   
   public function actionDeactive(){
      $post_id = Yii::app()->request->getParam('post_id',0);
      $message = 'Không thành công';
      $error = 1;
      if($post_id != 0){
         $model = Post::model()->findByPk($post_id);
         if($model->post_use_id == Yii::app()->user->id){
            $model->post_active = 0;
            if($model->save()){
               $error = 0;
               $message = 'Xóa thành công';
            }
         }
      }
      echo json_encode(array('error' => $error,'message' => $message));
   }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}